import threading
import time
from xtquant.xttrader import XtQuantTrader
from xtquant.xttype import StockAccount

from 研究.接口.交易接口.qmt.TradeCallback import MyXtQuantTraderCallback

session_id = 1


def connect(path, stock_aacount):
    # 重连时需要更换session_id
    global session_id
    session_id += 1
    xt_trader = XtQuantTrader(path, session_id)
    # 创建资金账号为1000000365的证券账号对象
    acc = StockAccount(stock_aacount)
    callback = MyXtQuantTraderCallback()
    xt_trader.register_callback(callback)
    # 启动交易线程
    xt_trader.start()
    # 建立交易连接，返回0表示连接成功
    connect_result = xt_trader.connect()
    if connect_result == 0:
        return xt_trader, True, acc, session_id
    else:
        xt_trader.stop()
        return None, False, acc, session_id


def auto_connect(path, stock_account):
    xt_trader, success, acc = connect(path, stock_account)
    while 1:
        if (xt_trader is None) and (success == False):
            xt_trader, success, acc = connect(path, stock_account)
        time.sleep(3)


def auto_connect_async(path, stock_account):
    threading.Thread(target=auto_connect, args=(path, stock_account))
